#include "xAccepter.h"
#include "xLog/xLog.h"
namespace xNet
{
    xAccepter::xAccepter(std::string strIp,uint16 wPort)
                : m_serviceSocket{strIp,wPort}
                , m_epFd(-1)
    {        
    }

    bool xAccepter::Init()
    {
        if( !m_serviceSocket.Init()
          || !m_serviceSocket.Bind() 
          || !m_serviceSocket.Listen())
        {
            XLOG_ERROR("xAccepter Init Fail");
            return false;
        }
        m_epFd = epoll_create(EPOLL_SIZE);
        if(m_epFd == -1)
        {
            XLOG_ERROR("EPOLL Create Fail,Please epoll_create API");
            return false;
        }
        return m_serviceSocket.AddEPOLL(m_epFd,nullptr); 
    }

    void xAccepter::Finish()
    {
        m_serviceSocket.Close();
        if(m_epFd != -1)
        {
            ::close(m_epFd);
            m_epFd = -1;
        }
    }

    int xAccepter::Accept()
    {
        switch(int conns = epoll_wait(m_epFd,&m_events[0],1,MAX_EPOLL_WAIT_TIME))
        {
            case 0: //timeout
                break;
            case -1: //error
                break;
            default:
                return conns;
        }
        return 0;
    }
}